package com.httpclient.postDemo;

import com.alibaba.fastjson.JSONObject;
import netscape.javascript.JSObject;
import org.apache.http.Consts;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicHeader;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;

public class PostDemo {

    /**
     *发送x-www-form-urlencoded格式的post请求（默认是这个）
     */
    public static void postOfForm(){

/*httpClient创建的两个方法：
第一个：
    CloseableHttpClient closeableHttpClient= HttpClientBuilder.create().build();
第二个：
    CloseableHttpClient httpClient = HttpClients.createDefault();
第三个：
创建池子：
* */
        CloseableHttpClient closeableHttpClient = HttpClients.createDefault();
        String url="https://www.baidu.com/";
        HttpPost httpPost=new HttpPost(url);
//        设置请求头
        httpPost.addHeader("Content-Type","application/x-www-form-urlencoded;charset=utf-8");
//        设置参数
        /*
        NameValuePair:前端传过来的一个键值对就是一个NameValuePair对象
         */
        List<NameValuePair> params=new ArrayList<>();
        params.add(new BasicNameValuePair("username","A夜兔A"));
        params.add(new BasicNameValuePair("password","666"));
//       把参数集合设置到formEntity中
        UrlEncodedFormEntity formEntity=new UrlEncodedFormEntity(params, Consts.UTF_8);
//       将参数设置到里面
        httpPost.setEntity(formEntity);

        CloseableHttpResponse response=null;
        try {
            response = closeableHttpClient.execute(httpPost);
            //获得响应结果
            HttpEntity entity = response.getEntity();
//            对HttpEntity操作的工具类
            String result = EntityUtils.toString(entity, "UTF-8");
            System.out.println(result);
            //确保流关闭
            EntityUtils.consume(entity);
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                if (response!=null){
                    response.close();
                }
                if (httpPost!=null){
                    httpPost.releaseConnection();
                }
                if (closeableHttpClient!=null){
                    closeableHttpClient.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
    }

    /**
     * 发送json的post请求
     */
    public static void postOfJson(){

        CloseableHttpClient closeableHttpClient = HttpClients.createDefault();
        String url="https://www.baidu.com/";
        HttpPost httpPost=new HttpPost(url);

//      设置参数String：是个json字符串
        JSONObject params=new JSONObject();
        params.put("username","A夜兔A");
        params.put("password","666");

        StringEntity jsonEntity=new StringEntity(params.toString(),Consts.UTF_8);
//      设置jsonEntity的类型(设置请求头的第二个方式）
        jsonEntity.setContentType(new BasicHeader("Content-Type","application/json;charset=utf-8"));
        //设置编码
        jsonEntity.setContentEncoding(Consts.UTF_8.name());
        httpPost.setEntity(jsonEntity);

        CloseableHttpResponse response=null;
        try {
            response = closeableHttpClient.execute(httpPost);
            //获得响应结果
            HttpEntity entity = response.getEntity();
//            对HttpEntity操作的工具类
            String result = EntityUtils.toString(entity, "UTF-8");
            System.out.println(result);
            //确保流关闭
            EntityUtils.consume(entity);
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                if (response!=null){
                    response.close();
                }
                if (httpPost!=null){
                    httpPost.releaseConnection();
                }
                if (closeableHttpClient!=null){
                    closeableHttpClient.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
    }


}
